package com.syys.example;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;
import org.junit.jupiter.api.Test;

import java.io.UnsupportedEncodingException;

/**
 * 订阅消息
 */
public class Consumer {

    private DefaultMQPushConsumer defaultMQPushConsumer;

    public void init() {
        defaultMQPushConsumer = new DefaultMQPushConsumer("TEST01_CONSUMER");
        defaultMQPushConsumer.setNamesrvAddr("127.0.0.1:9876");
        /**
         * 设置Consumer第一次启动 消费方式 ConsumeFromWhere
         * 非第一次启动，则按照上次消费的位置继续消费
         */
        defaultMQPushConsumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
        defaultMQPushConsumer.setMessageModel(MessageModel.BROADCASTING);
    }

    @Test
    public void consumer() throws MQClientException {
        init();
        defaultMQPushConsumer.subscribe("TopicQuickStart", "*");
        defaultMQPushConsumer.registerMessageListener((MessageListenerConcurrently) (msgs, consumeConcurrentlyContext) -> {
            for (MessageExt msg : msgs) {
                String topic = msg.getTopic();
                String tags = msg.getTags();
                String msgStr = null;
                try {
                    msgStr = new String(msg.getBody(), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }
                System.out.println(Thread.currentThread().getName() + " 处理消息： topic:" + topic + " tags:" + tags + " msg:" + msgStr);
            }
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        });
        defaultMQPushConsumer.start();

        // 线程阻塞 main方法中止
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
